package demo.velocity.controller;

import demo.velocity.bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 映射一个http访问路径 - /testVelocity
 */
@WebServlet(name = "TestServlet",urlPatterns = "/testVelocity")
public class TestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //向request作用域中添加txt变量
        req.setAttribute("txt","Hello Velocity 汪磊");

        //测试向servletContext中添加数据
        this.getServletContext().setAttribute("context","this is context data");
        //测试向Session中添加数据
        req.getSession().setAttribute("session","this is session data");
        //测试向request作用域中添加数据
        req.setAttribute("request","this is request data");

        //测试添加一个对象
        req.setAttribute("user",new User("xiaoming","123456"));
        Map<String, User> userMap = new HashMap<>();

        //测试添加一个map集合
        userMap.put("tom", new User("Tom", "456"));
        req.setAttribute("userMap", userMap);

        //测试添加一个list集合
        List<User> list = new ArrayList<>();
        list.add(new User("tom","123456"));
        list.add(new User("jkc","7708801314520"));
        list.add(new User("amy","7708801314520"));
        list.add(new User("tata","7708801314520"));
        req.setAttribute("userlist",list);

        //转发请求到test.vm模板
        req.getRequestDispatcher("/WEB-INF/views/test.vm").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
